package com.qiangesoft.tenantid.controller;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qiangesoft.tenantid.entity.SysDept;
import com.qiangesoft.tenantid.entity.SysUser;
import com.qiangesoft.tenantid.service.ISysDeptService;
import com.qiangesoft.tenantid.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * <p>
 * 用户信息 前端控制器
 * </p>
 *
 * @author qiangesoft
 * @since 2024-04-11
 */
@Slf4j
@RestController
@RequestMapping("/sys-user")
public class SysUserController {

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysDeptService sysDeptService;

    @GetMapping("/list")
    public List<SysUser> list() {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(SysUser::getCreateTime);
        List<SysUser> sysUserList = sysUserService.list(queryWrapper);
        log.info(JSON.toJSONString(sysUserList));

        List<SysDept> sysDeptList = sysDeptService.listByParam(1L);
        log.info(JSON.toJSONString(sysDeptList));

        return sysUserList;
    }

    @GetMapping("/sync")
    public List<SysDept> sync() throws ExecutionException, InterruptedException {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(SysUser::getCreateTime);
        List<SysUser> sysUserList = sysUserService.list(queryWrapper);
        log.info(JSON.toJSONString(sysUserList));

        // 异步查询部门
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        Callable getUser = () -> {
            RequestContextHolder.setRequestAttributes(sra, true);
            List<SysDept> sysDeptList = sysDeptService.list();
            log.info(JSON.toJSONString(sysDeptList));
            return sysUserList;
        };
        FutureTask<List<SysDept>> future = new FutureTask<>(getUser);
        new Thread(future).start();
        return future.get();
    }

}